package com.rainyun.rcmc.bukkit;

import com.rainyun.rc.command.CmdPath;
import org.bukkit.Bukkit;
import org.bukkit.command.*;
import org.bukkit.plugin.java.JavaPlugin;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class BukCmds implements CommandExecutor,TabCompleter {
	
	Map<String,BukCmdPath> main_cmds = new LinkedHashMap<String,BukCmdPath>();
	JavaPlugin plugin;
	
	public BukCmds(JavaPlugin plugin) {
		this.plugin = plugin;
	}
	
	@Override
	public boolean onCommand(CommandSender sd, Command cmd, String label, String[] args){
		CmdPath<CommandSender> comp = main_cmds.get(cmd.getName());
		if(comp!=null) {
			Bukkit.getScheduler()
					.runTaskAsynchronously(plugin,() -> comp.input(sd, args));
			return true;
		}else
			return false;
	}

	@Override
	public List<String> onTabComplete(CommandSender sd, Command cmd, String alias, String[] args) {
		CmdPath<CommandSender> comp = main_cmds.get(cmd.getName());
		if(comp!=null)
			return comp.tabInput(sd, args);
		else
			return null;
	}

	public BukCmds bindCmd(String name,BukCmdPath cmd) {
		PluginCommand bukcom = plugin.getCommand(name);
		if(bukcom!=null) {
			main_cmds.put(name,cmd);
			bukcom.setExecutor(this);
			bukcom.setTabCompleter(this);
			cmd.setName(name);
		}else {
			System.out.println("Unknown Bukkit command :"+name+",Have you defined it correctly?");
		}
		return this;
	}
	
	public void unbindCmd(String name) {
		main_cmds.remove(name);
	}
	
	public Map<String,BukCmdPath> getMainCmds() {
		return main_cmds;
	}
	public void setMainCmds(Map<String,BukCmdPath> main_cmds) {
		this.main_cmds = main_cmds;
	}
	
}
